package sort;

import java.util.Arrays;
import java.util.Objects;

/**
 * 冒泡排序
 *
 * @auther yang
 * @date 2022/3/16 13:33
 */
public class BubbleSort {

    public static void main(String[] args) {
        int[] arr = {3, 5, 0, 8, 99, 1, 0};
        int[] copyArr = Arrays.copyOf(arr, arr.length);
        bubbleSort(copyArr);
        System.out.println(Arrays.toString(copyArr));
        System.out.println(test(arr, copyArr));
    }

    public static boolean test(int[] originalArr, int[] sortedArr) {
        Arrays.sort(originalArr);
        return Arrays.equals(originalArr, sortedArr);
    }


    public static void bubbleSort(int[] a) {
        if (Objects.isNull(a))
            throw new IllegalArgumentException("参数不能为null");
        if (a.length < 2)
            return;
        sort(a, a.length);
    }

    // 冒泡排序的递归算法
    public static void sort(int[] a, int n) {
        if (n < 2) return;
        for (int i = 1; i < n; ++i) {
            if (a[i - 1] > a[i]) {
                swap(a, i - 1, i);
            }
        }
        sort(a, n - 1);
    }

    public static void swap(int[] a, int i, int j) {
        a[i] = a[i] ^ a[j];
        a[j] = a[i] ^ a[j];
        a[i] = a[i] ^ a[j];
    }

}
